package com.weetop.cfw.register

import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.view.View
import com.blankj.utilcode.util.*
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.UpdatePasswordPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.UpdatePasswordView
import com.weetop.cfw.bean.ErrorBean
import com.weetop.cfw.bean.VerificationCodeBean
import com.weetop.cfw.log_in.PasswordLogInActivity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_update_password.*
import java.util.concurrent.TimeUnit


/**
 * 修改密码界面
 */
class UpdatePasswordActivity : CommonBaseActivity(),View.OnClickListener,TextWatcher,UpdatePasswordView {

    private var isPassword = true
    private var isPasswordAgain = true

    private lateinit var updatePasswordPresenterImp: UpdatePasswordPresenterImp

    private var dispose:Disposable? = null//用来解除RxJava与该界面的绑定

    override fun onClick(p0: View?) {
        when(p0?.id){
            R.id.imageUpdatePasswordBack -> ActivityUtils.finishActivity(this)
            R.id.imageShowOrHidePassword -> {
                if(isPassword){
                    editPassword.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                    isPassword = false
                    imageShowOrHidePassword.setImageResource(R.mipmap.password_hide_logo)
                }else{
                    editPassword.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                    isPassword = true
                    imageShowOrHidePassword.setImageResource(R.mipmap.password_show_logo)
                }
            }
            R.id.imageShowOrHidePasswordAgain -> {
                if (isPasswordAgain) {
                    editPasswordAgain.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                    isPasswordAgain = false
                    imageShowOrHidePasswordAgain.setImageResource(R.mipmap.password_hide_logo)
                } else {
                    editPasswordAgain.inputType =
                        InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                    isPasswordAgain = true
                    imageShowOrHidePasswordAgain.setImageResource(R.mipmap.password_show_logo)
                }
            }
            R.id.imageClearVerificationCode -> editVerificationCode.setText("")
            R.id.textGetVerificationCode ->{
                val mobile = editPhoneNumber.text.toString().trim();
                if(mobile.isEmpty()){
                    showNativeShortToast("请输入手机号")
                    return
                }
                if(!RegexUtils.isMobileExact(mobile) ){
                    showNativeShortToast("请输入合法手机号")
                    return
                }
                textGetVerificationCode.isEnabled = false
                updatePasswordPresenterImp.getVerificationCode(this@UpdatePasswordActivity,mobile)
            }
            R.id.textSureUpdate -> updatePasswordPresenterImp.resetPassword(this@UpdatePasswordActivity,editPhoneNumber.text.toString().trim(),EncryptUtils.encryptMD5ToString(editPassword.text.toString().trim()).toLowerCase(),EncryptUtils.encryptMD5ToString(editPasswordAgain.text.toString().trim()).toLowerCase(),editVerificationCode.text.toString().trim())
        }
    }

    override fun getLayoutId() = R.layout.activity_update_password

    override fun initView(savedInstanceState: Bundle?) {
        updatePasswordPresenterImp = UpdatePasswordPresenterImp()
        updatePasswordPresenterImp.attachView(this)

        setViewsOnClickListener(this,imageUpdatePasswordBack,imageShowOrHidePassword,imageShowOrHidePasswordAgain,imageClearVerificationCode,textGetVerificationCode,textSureUpdate)

        editVerificationCode.addTextChangedListener(this)
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    override fun afterTextChanged(p0: Editable?) {
        if(p0 != null){
            if(p0.toString().isNotEmpty()){
                imageClearVerificationCode.visibility = View.VISIBLE
            }else{
                imageClearVerificationCode.visibility = View.INVISIBLE
            }
        }
    }

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

    }

    /**
     * 获取验证码成功
     */
    override fun getVerificationCodeSuccess(verificationCodeBean: VerificationCodeBean?) {
        showNativeShortToast(verificationCodeBean?.message)
        dispose = Observable.interval(1, TimeUnit.SECONDS)
            .take(61)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                if((60 -it) == 0L){
                    textGetVerificationCode.text = "发送验证码"
                    textGetVerificationCode.setTextColor(ColorUtils.getColor(R.color.c_1381CC))
                    textGetVerificationCode.isEnabled = true
                }else{
                    textGetVerificationCode.isEnabled = false
                    textGetVerificationCode.setTextColor(ColorUtils.getColor(R.color.secondary_text_color))
                    textGetVerificationCode.text = "${60 - it}秒后重新发送"
                }
            }
    }

    /**
     * 获取验证码失败
     */
    override fun getVerificationCodeFailed(verificationCodeBean: VerificationCodeBean?) {
        showNativeShortToast(verificationCodeBean?.message)
    }

    /**
     * 密码更新成功
     */
    override fun resetPasswordSuccess(errorBean: ErrorBean?) {
        showNativeShortToast("密码修改成功")
        dispose = Observable.timer(500,TimeUnit.MILLISECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                ActivityUtils.startActivity(PasswordLogInActivity::class.java)
                ActivityUtils.finishAllActivities()
            }
    }

    override fun onDestroy() {
        super.onDestroy()
        updatePasswordPresenterImp.detachView()
        if(dispose != null && !dispose!!.isDisposed){
            dispose!!.dispose()
        }
    }

}
